/**
 * 
 */
package com.haizhi.user.controller;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.haizhi.bean.TbPost;
import com.haizhi.bean.TbReply;
import com.haizhi.bean.TbSection;
import com.haizhi.bean.TbUser;
import com.haizhi.service.PostService;
import com.haizhi.service.ReplyService;
import com.haizhi.service.SectionService;
import com.haizhi.user.vo.PostDetailVo;
import com.haizhi.user.vo.PostVo;
import com.haizhi.user.vo.ReplyVo;
import com.haizhi.user.vo.SectionVo;
import com.haizhi.util.BaseVoUtil;
import com.haizhi.util.MyMapBuilder;
import com.haizhi.util.ResponseEntityUtil;
import com.haizhi.util.MyMapBuilder.ErrorCode;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

/**
 * @author jiangjintai
 *
 */
@Controller
@RequestMapping("/bbs")
@Api(description="帖子版块", value = "帖子版块")//添加注释  
public class BbsController {
	public  static String s = "123";
	static Logger logger = Logger.getLogger(BbsController.class);
	@Autowired
	ReplyService replyService;
	@Autowired
	PostService postService;
	@Autowired
	SectionService sectionService;
	
	@RequestMapping("/getSections")
	@ApiOperation(value = "获取全部版块",httpMethod="POST")//添加注释这里要把方法写上，string类型大写  
	public ResponseEntity<Map<String,Object>> getSections(
			HttpServletRequest request
	) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
		List<TbSection> tbSectionList = sectionService.findAll();
		logger.info("全部版块获取成功");
		List<SectionVo> sectionVoList = new ArrayList<SectionVo>();
		for(TbSection tbSection : tbSectionList){
			SectionVo sectionVo =BaseVoUtil.getVo(tbSection,new SectionVo());
			sectionVoList.add(sectionVo);
		}
		return new ResponseEntity<>(MyMapBuilder.buildSuccessMap("获取成功").put("section",sectionVoList ),HttpStatus.OK);
	}
	
	@RequestMapping("/getPostList")
	@ApiOperation(value = "获取帖子列表",httpMethod="POST")//添加注释这里要把方法写上，string类型大写  
	public ResponseEntity<Map<String,Object>> getPostList(
			@ApiParam(value="版块id",name="sectionId",required=true)@RequestParam(name="sectionId")String sectionId,
			@ApiParam(value="页码数，开始为0，默认为0",name="page",required=true)@RequestParam(defaultValue="0",name="page")String page,
			@ApiParam(value="每页数量，默认20",name="size",required=true)@RequestParam(defaultValue="20",name="size")String size,
			@PageableDefault Pageable pageAble
			) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
		int sectionIdInt = Integer.valueOf(sectionId);
		TbSection tbSection = sectionService.findById(sectionIdInt);
		if(tbSection==null)
			return ResponseEntityUtil.buildErrorEntity(ErrorCode.paramError, "该模块不存在");
		Page<TbPost>  postPage = postService.findByTbSectionAndPostType(tbSection,1,pageAble);
		List<TbPost> postList=postPage.getContent();

		List<PostVo> postVoList = new ArrayList<PostVo>();
		for(TbPost  tbPost : postList){
			PostVo postVo = BaseVoUtil.getVo(tbPost, new PostVo());
			TbReply tbReply = replyService.findTopByTbPostAndReplyType(tbPost,1);
			if(tbReply!=null){
				postVo.setLastReplyUserId(tbReply.getTbUser().getUserId());
				postVo.setLastReplyUserName(tbReply.getTbUser().getUserName());
				postVo.setLastReplyUserSex(tbReply.getTbUser().getUserSex());
				postVo.setLastReplyTime(tbReply.getReplyTime());
			}
			
			postVo.setUserId(tbPost.getTbUser().getUserId());
			postVo.setUserName(tbPost.getTbUser().getUserName());
			postVo.setUserSex(tbPost.getTbUser().getUserSex());
			postVoList.add(postVo);		
		}
		logger.info("全部帖子获取成功");
		return new ResponseEntity<Map<String,Object>>(MyMapBuilder.buildSuccessMap("获取成功").put("post",postVoList).put("totalPage", postPage.getTotalPages()).put("nowPage", postPage.getNumber()),HttpStatus.OK);
	}
	

	@RequestMapping("/getPostDetail")
	@ApiOperation(value = "获取帖子细节",httpMethod="POST")//添加注释这里要把方法写上，string类型大写  
	public ResponseEntity<Map<String,Object>> getPostDetail(
			@ApiParam(value="帖子id",name="postId",required=true)@RequestParam(name="postId")String postId
			) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
		int postIdInt = Integer.valueOf(postId);
		TbPost tbPost = postService.findById(postIdInt);
		if(tbPost==null)
			return ResponseEntityUtil.buildErrorEntity(ErrorCode.paramError, "id错误");
		if(tbPost.getPostType()==0)
			return ResponseEntityUtil.buildErrorEntity(ErrorCode.noAuthorityError, "帖子被拉黑了");
		PostDetailVo postDetailVo = BaseVoUtil.getVo(tbPost, new PostDetailVo());
		postDetailVo.setUserId(tbPost.getTbUser().getUserId());
		postDetailVo.setUserName(tbPost.getTbUser().getUserName());
		postDetailVo.setUserSex(tbPost.getTbUser().getUserSex());
		return new ResponseEntity<Map<String,Object>>(MyMapBuilder.buildSuccessMap("获取成功").put("post", postDetailVo),HttpStatus.OK);
	}
	
	@RequestMapping("getPostReplyList")
	@ApiOperation(value = "获取帖子评论",httpMethod="POST")//添加注释这里要把方法写上，string类型大写  
	public ResponseEntity<Map<String,Object>> getPostReplyList(
			@ApiParam(value="帖子id",name="postId",required=true)@RequestParam(name="postId")String postId,
			@ApiParam(value="页码数，开始为0，默认为0",name="page",required=true)@RequestParam(defaultValue="0",name="page")String page,
			@ApiParam(value="每页数量，默认20",name="size",required=true)@RequestParam(defaultValue="20",name="size")String size,
			@PageableDefault Pageable pageAble
			) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
		int postIdInt = Integer.valueOf(postId);
		TbPost tbPost = postService.findById(postIdInt);
		if(tbPost==null)
			return ResponseEntityUtil.buildErrorEntity(ErrorCode.paramError, "id错误");
		if(tbPost.getPostType()==0)
			return ResponseEntityUtil.buildErrorEntity(ErrorCode.noAuthorityError, "帖子被拉黑了");
		Page<TbReply> tbReplyPage = this.replyService.findByPostAndReplyType(tbPost,1,pageAble);
		List<ReplyVo> replyVoList = new ArrayList<ReplyVo>();
		List<TbReply> tbReplyList =tbReplyPage.getContent();
		for(TbReply tbReply : tbReplyList){
			ReplyVo replyVo  = BaseVoUtil.getVo(tbReply, new ReplyVo());
			replyVo.setReplyUserId(tbReply.getTbUser().getUserId());
			replyVo.setReplyUserName(tbReply.getTbUser().getUserName());
			replyVo.setReplyUserSex(tbReply.getTbUser().getUserSex());
			replyVoList.add(replyVo);
		}
		return new ResponseEntity<Map<String,Object>>(MyMapBuilder.buildSuccessMap(replyVoList).put("totalPage", tbReplyPage.getTotalPages()).put("nowPage", tbReplyPage.getNumber()),HttpStatus.OK);
	}
	
	@RequestMapping("/addPost")
	@ApiOperation(value = "添加帖子",httpMethod="POST")//添加注释这里要把方法写上，string类型大写  
	public ResponseEntity<Map<String,Object>> addPost(
			@ApiParam(value="版块id",name="sectionId",required=true)@RequestParam(name="sectionId")String sectionId,
			@ApiParam(value="主题",name="title",required=true)@RequestParam(name="title")String title,
			@ApiParam(value="内容",name="content",required=true)@RequestParam(name="content")String content,
			HttpServletRequest request
			){
		TbUser tbUser = (TbUser) request.getAttribute("tbUser");
		TbSection tbSection = sectionService.findById(Integer.valueOf(sectionId));
		if(tbSection==null)
			return ResponseEntityUtil.buildErrorEntity(ErrorCode.paramError, "没有该版块id对应的版块");
		if(title==null||title.trim().isEmpty())
			return ResponseEntityUtil.buildErrorEntity(ErrorCode.paramError, "主题不能为空");
		TbPost tbPost = new TbPost();
		tbPost.setPostContent(content);
		tbPost.setPostReplyNum(0);
		tbPost.setPostTime(new Date());
		tbPost.setPostTitle(title);
		tbPost.setPostType(1);
		tbPost.setTbSection(tbSection);
		tbPost.setTbUser(tbUser);
		postService.saveAndUpdateTbSection(tbPost);
		logger.info("添加成功");
		return 	new ResponseEntity<>(MyMapBuilder.buildSuccessMap("添加成功").put("postId", tbPost.getPostId()), HttpStatus.OK);
	}
	
	@RequestMapping("/addReply")
	@ApiOperation(value = "添加回复",httpMethod="POST")//添加注释这里要把方法写上，string类型大写  
	public ResponseEntity<Map<String,Object>> addReply(
			@ApiParam(value="版块id",name="postId",required=true)@RequestParam(name="postId")String postId,
			@ApiParam(value="评论内容",name="replyContent",required=true)@RequestParam(name="replyContent")String replyContent,
			HttpServletRequest request
			) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
		TbUser tbUser = (TbUser) request.getAttribute("tbUser");
		TbPost tbPost = postService.findById(Integer.valueOf(postId));
		if(tbPost==null)
			return new ResponseEntity<>(MyMapBuilder.buildErrorMap(ErrorCode.paramError, "查无该postId"), HttpStatus.OK);
		TbReply tbReply = new TbReply();
		tbReply.setReplyContent(replyContent);
		tbReply.setReplyFloos(1);
		tbReply.setReplyTime(new Date());
		tbReply.setReplyType(1);
		tbReply.setTbPost(tbPost);
		tbReply.setTbUser(tbUser);
		replyService.saveAndUpdateTbPostAndTbSection(tbReply);
		logger.info("创建成功");
		ReplyVo replyVo = BaseVoUtil.getVo(tbReply, new ReplyVo());
		return new ResponseEntity<>(MyMapBuilder.buildSuccessMap("创建成功").put("reply", replyVo),HttpStatus.OK);
		
	}
	
	/** 
     * 异常页面控制 
     *  
     * @param runtimeException 
     * @return 
     */  
    @ExceptionHandler(RuntimeException.class)  
    @ResponseBody
    public  ResponseEntity<Map<String,Object>> runtimeExceptionHandler(RuntimeException runtimeException) {  
    	logger.error(runtimeException.getMessage());
    	logger.error(runtimeException.getStackTrace());
    	logger.info(runtimeException.getStackTrace());
    	runtimeException.printStackTrace();
    	return new ResponseEntity<Map<String,Object>>(MyMapBuilder.buildErrorMap(ErrorCode.paramError, runtimeException.getMessage()),HttpStatus.BAD_REQUEST);
         
    }  
}
